import { filterAuth, findDicByCodeSort, getDicByKey } from '@/support/common';
import { ExportOutlined } from '@ant-design/icons';
import { Button, Card, message } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';
import router from 'umi/router';
import * as XLSX from 'xlsx';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import PateoTable from '../../../components/common/PateoTable';
import styles from '../../../components/common/PateoTable/TableList.less';

const mapStateToProps = (state: any) => ({
  fenceVehicleMng: state.fenceVehicleMng,
  loading: state.loading.effects['fenceVehicleMng/postFetchPage'],
});
class FenceVehicleMng extends PureComponent<any, any> {
  static contextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.array,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      seriesList: [],
      typeList: [],
      allType: [],
      exportLoading: false,
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'fenceVehicleMng/postFetchPage',
      payload: { url: '/electricfence/findfencevehiclebypage' },
    });
    dispatch({
      type: 'fenceVehicleMng/getData',
      payload: { url: '/common/vehicle/getserieslist', brandId: 'MATC' },
      callback: (res: any) => {
        this.setState({ seriesList: res.data });
      },
    });
    dispatch({
      type: 'fenceVehicleMng/getData',
      payload: { url: '/common/vehicle/gettypelist', brandId: 'MATC' },
      callback: (res: any) => {
        this.setState({ allType: res.data });
      },
    });
  }

  handleLocation = (vin: any, fenceId: any) => {
    router.push({
      pathname: `${self === top ? '' : '/external'}/electricFence/fenceVehicleMng/location`,
      query: { vin, fenceId },
    });
  };

  handleTrack = (vin: any, fenceId: any) => {
    router.push({
      pathname: `${self === top ? '' : '/external'}/electricFence/fenceVehicleMng/track`,
      query: { vin, fenceId },
    });
  };

  onSeriesChange = (value: any) => {
    const { dispatch } = this.props;
    this.searchForm.current.resetFields(['vehicleType']);
    if (value != null && value != undefined) {
      dispatch({
        type: 'fenceVehicleMng/getData',
        payload: { url: '/common/vehicle/gettypelist', brandId: 'MATC', seriesId: value },
        callback: (response: any) => {
          this.setState({ typeList: response.data });
        },
      });
    } else {
      this.setState({ typeList: [] });
    }
  };

  handleExport = () => {
    const { dispatch } = this.props;
    this.setState({ exportLoading: true });
    dispatch({
      type: 'http/postObj',
      payload: {
        url: '/electricfence/exportfenceofvehicle',
        ...this.state.formValues,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          const data = [];
          res.data.forEach((e, i) => {
            // 车系 series
            let series = e.series;
            if (series) {
              let current = this.state.seriesList.find((item: any) => item.code == series);
              if (current) {
                series = current.name;
              }
            }
            // 车型 vehicleType
            let vehicleType = e.vehicleType;
            if (vehicleType) {
              let current = this.state.allType.find((item: any) => item.code == vehicleType);
              if (current) {
                series = current.name;
              }
            }
            // 车辆类型 vhlType
            const vhlType = e.vhlType
              ? getDicByKey(this.context.dicData, 'fenceVhlType', String(e.vhlType))
              : '';
            // 激活状态 enrollStatus
            const enrollStatus =
              e.enrollStatus != null
                ? getDicByKey(this.context.dicData, 'fenceVhlEnrollStatus', String(e.enrollStatus))
                : '未激活';

            data.push({
              vin: e.vin,
              series,
              vehicleType,
              vhlType,
              enrollStatus,
              fenceCode: e.fenceCode,
              fenceName: e.fenceName,
              fenceExpireDate:
                e.warningBeginDate && e.warningEndDate
                  ? `${moment(e.warningBeginDate).format('YYYY-MM-DD')} ~ ${moment(
                      e.warningEndDate,
                    ).format('YYYY-MM-DD')}`
                  : '无限制',
              fenceStatus: getDicByKey(
                this.context.dicData,
                'fenceVhlStatus',
                String(e.fenceStatus),
              ),
            });
          });

          const header = {
            vin: 'vin',
            series: '车系',
            vehicleType: '车型',
            vhlType: '车辆类型',
            enrollStatus: '激活状态',
            fenceCode: '围栏编号',
            fenceName: '围栏名称',
            fenceExpireDate: '围栏有效期',
            fenceStatus: '在栏状态',
          };
          const ws = XLSX.utils.json_to_sheet([header, ...data], { skipHeader: true });
          const wb = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(wb, ws, 'export');
          XLSX.writeFile(wb, 'export.xlsx');
        } else {
          message.error('导出失败');
        }
      },
    }).finally(() => this.setState({ exportLoading: false }));
  };

  render() {
    const {
      fenceVehicleMng: {
        pageData: { list, pagination },
      },
      loading,
      location: { pathname = '/' },
      dispatch,
    } = this.props;
    const { formValues, seriesList, typeList, allType } = this.state;
    const columns = [
      {
        title: 'VIN',
        dataIndex: 'vin',
      },
      {
        title: '车系',
        dataIndex: 'series',
        render: (text: any) => {
          let series = text;
          if (text) {
            let current = seriesList.find((item: any) => item.code == text);
            if (current) {
              series = current.name;
            }
          }
          return series;
        },
      },
      {
        title: '车型',
        dataIndex: 'vehicleType',
        render: (text: any) => {
          let series = text;
          if (text) {
            let current = allType.find((item: any) => item.code == text);
            if (current) {
              series = current.name;
            }
          }
          return series;
        },
      },
      {
        title: '车辆类型',
        dataIndex: 'vhlType',
        render: (text: any) => {
          return text ? getDicByKey(this.context.dicData, 'fenceVhlType', String(text)) : null;
        },
      },
      {
        title: '激活状态',
        dataIndex: 'enrollStatus',
        render: (text: any) => {
          return text != null
            ? getDicByKey(this.context.dicData, 'fenceVhlEnrollStatus', String(text))
            : '未激活';
        },
      },
      {
        title: '围栏编号',
        dataIndex: 'fenceCode',
      },
      {
        title: '围栏名称',
        dataIndex: 'fenceName',
      },
      {
        title: '围栏有效期',
        render: (text: any) => {
          return text.warningBeginDate && text.warningEndDate
            ? `${moment(text.warningBeginDate).format('YYYY-MM-DD')} ~ ${moment(
                text.warningEndDate,
              ).format('YYYY-MM-DD')}`
            : '无限制';
        },
      },
      {
        title: '在栏状态',
        dataIndex: 'fenceStatus',
        render: text => {
          const value = getDicByKey(this.context.dicData, 'fenceVhlStatus', String(text));
          if (value && value != 'null') {
            return value;
          } else {
            return '';
          }
        },
      },
      {
        title: '操作',
        dataIndex: '操作',
        width: 172,
        fixed: 'right',
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '车辆位置',
              key: 'location',
              auth: 'fenceVehicleMng_doLocation',
              onConfirm: () => this.handleLocation(record.vin, record.fenceId),
            },
            {
              title: '行车轨迹',
              key: 'track',
              auth: 'fenceVehicleMng_doTrack',
              onConfirm: () => this.handleTrack(record.vin, record.fenceId),
            },
          ];
          return <PateoAuthButtons btns={btns} max={1} pathname={pathname} />;
        },
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    const tableProps = {
      columns,
      dataSource: list,
      loading,
      rowKey: (record: any) => record.id,
      pagination: paginationProps,
      scroll: { x: 'max-content' },
    };
    const searchItems = [
      {
        type: 'input',
        title: 'VIN',
        key: 'vin',
      },
      {
        type: 'select',
        title: '车系',
        key: 'vehicleSeries',
        selectOptions: seriesList,
        keyValue: ['code', 'name'],
        onChange: this.onSeriesChange,
      },
      {
        type: 'select',
        title: '车型',
        key: 'vehicleType',
        selectOptions: typeList,
        keyValue: ['code', 'name'],
      },
      {
        type: 'select',
        title: '车辆类型',
        key: 'vhlType',
        selectOptions: findDicByCodeSort(this.context.dicData, 'fenceVhlType'),
        keyValue: ['dictKey', 'dictValue'],
      },
      {
        type: 'select',
        title: '激活状态',
        key: 'enrollStatus',
        selectOptions: findDicByCodeSort(this.context.dicData, 'fenceVhlEnrollStatus'),
        keyValue: ['dictKey', 'dictValue'],
      },
      {
        type: 'input',
        title: '围栏编号',
        key: 'fenceCode',
      },
      {
        type: 'input',
        title: '围栏名称',
        key: 'fenceName',
      },
      {
        type: 'select',
        title: '在栏状态',
        key: 'fenceStatus',
        selectOptions: findDicByCodeSort(this.context.dicData, 'fenceVhlStatus'),
        keyValue: ['dictKey', 'dictValue'],
      },
    ];
    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            fetchParams={{
              type: 'fenceVehicleMng/postFetchPage',
              url: '/electricfence/findfencevehiclebypage',
            }}
            saveFormValues={(val: any) =>
              this.setState({ formValues: Object.assign(formValues, val) })
            }
            handleFormReset={() => this.setState({ formValues: {}, typeList: [] })}
          />
        </Card>
        <Card className={styles.standardTable}>
          {filterAuth('fenceVehicleMng_doExport', this.context.permissions, pathname) ? (
            <div className="my_newItem">
              <Button
                size="small"
                icon={<ExportOutlined />}
                type="primary"
                onClick={() => this.handleExport()}
                loading={this.state.exportLoading}
              >
                导出
              </Button>
            </div>
          ) : null}
          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            fetchParams={{
              type: 'fenceVehicleMng/postFetchPage',
              url: '/electricfence/findfencevehiclebypage',
            }}
            formValues={formValues}
          />
        </Card>
      </div>
    );
  }
}
export default connect(mapStateToProps)(FenceVehicleMng);
